<template>
  <div class="app-container">
    <div class="flex">
      <el-input
        v-model="listQuery.title"
        :placeholder="t('message.layout.title')"
        style="width: 100px"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      
      <el-select
        v-model="listQuery.importance"
        :placeholder="t('message.layout.managementUnit')"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option
          v-for="item in importanceOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
      
      
      <el-select
        v-model="listQuery.author"
        :placeholder="t('message.layout.type')"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in calendarTypeOptions"
          :key="item"
          :label="item"
          :value="item"
        />
      </el-select>
     
      <el-button
        v-waves
        style="margin:0 0 20px 20px;"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        {{ $t('message.layout.search') }}
      </el-button>
      <el-button
        v-waves
        style="margin:0 0 20px 20px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        地图添加
      </el-button>
      <el-button
      v-waves
			        :loading="downloadLoading"
			        style="margin:0 0 20px 20px;"
			        type="primary"
			        icon="el-icon-document"
			        @click="handleDownload"
			      >
        		  {{ $t('message.layout.excelexport') }}     
      			</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
      @cell-mouse-enter="cellMouseEnter"
			@mouseleave="cellMouseLevel"
    >    
      <el-table-column
        label="领队"
        prop="abstractContent"
        sortable="custom"
        align="center"
        width="80"
        :class-name="getSortClass('abstractContent')"
      >
        <template #default="{row}">
          <span>{{ row.abstractContent }}</span>
        </template>
      </el-table-column>
      
      
      <el-table-column
        :label="t('message.layout.phone')"
        width="180px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.timestamp }}</span>
        </template>
      </el-table-column>
     
      <el-table-column
        :label="t('message.layout.title')"
        min-width="100px"
        width="180px"
      >
        <template #default="{row}">
          <span
            class="link-type"
            @click="handleUpdate(row)"
          >{{
            row.title
          }}</span>
          <!-- <el-tag>{{ row.type }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('message.layout.author')"
        width="180px"
        align="center"
      >
        <template #default="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <!--
      <el-table-column
        :label="t('message.layout.reviewer')"
        width="110px"
        align="center"
      >
        <template #default="{row}">
          <span style="color: red">{{ row.reviewer }}</span>
        </template>
      </el-table-column>
      -->
      <!-- <el-table-column
        :label="t('message.layout.managementUnit')"
        width="105px"
      >
        <template #default="{row}">
          <span style="color: red">{{ row.importance }}</span>
        </template>
      </el-table-column> -->
      
      <el-table-column
        :label="t('message.layout.pepoleNum')"
        align="center"
        width="200"
      >
        <template #default="{row}">
          <span
            v-if="row.pageviews"
            class="link-type"
            @click="handleGetPageviews(row.pageviews)"
          >{{ row.pageviews }}</span>
          <span v-else>0</span>
        </template>
      </el-table-column>
      
      <!-- <el-table-column
        :label="t('message.layout.organizationalSystem')"
        class-name="status-col"
        width="100"
      >
        <template #default="{row}">
          <el-tag :type="row.status">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column> -->
      
      <el-table-column
        :label="t('message.layout.actions')"
        align="center"
        width="230"
        class-name="fixed-width"
      >
        <template #default="{row, $index}">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            {{ t("message.layout.edit") }}
          </el-button>  
 
           <el-button            
            size="mini"
            @click="handleModifyStatus(row, 'draft')"
          >
            {{ t("message.layout.draft") }}
          </el-button>
          <el-button
            v-if="row.status !== 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row, $index)"
          >
            {{ t("message.layout.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="listQuery.currentPage"
      v-model:limit="listQuery.pageCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
    />
        <ZhuanyeDialog @updateData="updateData" @createData="createData" ref="dialogPop" v-model="dialogFormVisible" v-model:dialogStatus="dialogStatus"></ZhuanyeDialog>
    <div class=" fixed inset-0 flex " style="pointer-events: none;">
			<el-popover placement="bottom" trigger="click" v-model:visible="isShowUserNewsPopover" hide-after="86400" width="max-content" >
				<template #reference>
					<div class=" w-full h-32 "></div>
				</template>
					<el-table :data="gridData" @mouseleave="cellMouseLevel" @mouseenter="cellMouseEnter()">
            <el-table-column min-width="200" property="rowZero" label="人员" />
            <el-table-column min-width="100" property="rowOne" label="号码" />
            <el-table-column min-width="250" property="rowTwo" label="备注" />
          </el-table>
			</el-popover>
    </div>
  </div>
</template>

<script lang='ts'>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  nextTick,
  onMounted,
  unref
} from 'vue'
import { ElForm, ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash'
import {
  getArticles,
  getPageviews,
  createArticle,
  deleteArticle,
  updateArticle,
  defaultArticleModel,
  ArticleType
} from '/@/request/articles'
import { ArticleModel } from '/@/model/articleModel'
import { exportJson2Excel } from '/@/utils/excel'
import { formatJson } from '/@/utils'
//import { exportJson2Excel } from '@/utils/excel'
//import { formatJson } from '@/utils'
import { useI18n } from 'vue-i18n'
//import zhihuiJigouJson from '/@/mock/zhuanyeDuiwu.json';
// import Pagination from '@/components/Pagination/index.vue'
import '/@/assets/iconfont/iconfont.css'
import ZhuanyeDialog from './components/ZhuanyeDialog.vue'
import { useRouter } from 'vue-router'
export default defineComponent({
  components: {
    // Pagination
    ZhuanyeDialog
  },
  setup() {
     const router = useRouter();
     const dialogPop = ref(null);
    let popTime:any = null;
    const { t } = useI18n()
    const calendarTypeOptions = ['抢险抢修','医疗救护','消防','防化防疫','通信保障','交通运输','治安安全','应急合成']

    const calendarTypeKeyValue = calendarTypeOptions.reduce(
      (acc: { [key: string]: string }, cur) => {
        acc[cur.key] = cur.displayName
        return acc
      },
      {}
    ) as { [key: string]: string }
    const dataForm = ref(ElForm)
    const dataMap = reactive({
      isShowUserNewsPopover:false,
      //[{"id":0.4182513969189565,"rowZero":"衣服","rowTwo":"我和老师了","rowOne":"111"}]
      gridData : [
      ],
      rowlist:Array<any>({id:Math.random(),
          rowZero: '',
          rowTwo: '',
          rowOne:''
      }),
      rowlist:Array<any>({id:Math.random(),
          rowZero: '',
          rowTwo: '',
          rowOne:''
      }),
      tableKey: 0,
      list: Array<ArticleModel>(),
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
        pageCount: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },

      importanceOptions: ['人防办', '医疗办', '消防办', '防疫办', '通信办', '交通办', '治安办', '应急办'],
      calendarTypeOptions: calendarTypeOptions,
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],

      statusOptions: ['抢险组', '医疗组', '消防组', '防疫组', '通信组', '交通组', '治安组', '应急组'],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },

      dialogPageviewsVisible: false,
      pageviewsData: [],
      rules: {
        author: [
          { required: true, message: 'type is required', trigger: 'change' }
        ],
        abstractContent:[
          { required: true, message: 'number is required', trigger: 'blur' }
        ],
        title: [
          { required: true, message: 'title is required', trigger: 'blur' }
        ],
        status: [
          { required: true, message: 'area is required', trigger: 'blur' }
        ],
        importance: [
          { required: true, message: 'ControlUnit is required', trigger: 'change' }
        ],
        pageviews: [
          { required: true, message: 'location is required', trigger: 'change' }
        ],
      },
      downloadLoading: false,
      tempArticleModel: defaultArticleModel,
      handleCurrentChange(page?: any) {
        dataMap.getList(page)
      },
      handleSizeChange(val: any) {
        dataMap.getList(null, null, val)
      },
       cellMouseEnter(row){
        console.log('cellMouseEnter ',row);
        if(row){
          try{
            dataMap.gridData = [];
            let arr = JSON.parse(row.fullContent);
            dataMap.gridData = arr;
          }
          catch
          {
          }
        }
        dataMap.isShowUserNewsPopover = true;
        if(popTime)
        {
          clearTimeout(popTime);
          popTime = null;
        }
      },
      cellMouseLevel(row){
        console.log('cellMouseLevel ');
        if(popTime)
        {
          clearTimeout(popTime);
          popTime = null;
        }
        popTime = setTimeout(()=>{
           dataMap.isShowUserNewsPopover = false;
        },100);
      },
      async getList(page?: any, total?: any, limit?: any,data?:any) {
        if (page) {
          dataMap.listQuery.currentPage = page
        }
        if (limit) {
          dataMap.listQuery.pageCount = limit
        }
        console.log(total)
        dataMap.listLoading = true

        if (data){
        	dataMap.list = data.data
        	dataMap.total = data.total
        }
        else{
        const data = await getArticles(dataMap.listQuery,ArticleType.ZYDW)
        //const data=zhihuiJigouJson        
        dataMap.list = data?.data ?? []
        dataMap.total = data?.total ?? 0
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          dataMap.listLoading = false
        }, 0.5 * 1000)
      },
      handleFilter() {
        dataMap.listQuery.currentPage = 1
        dataMap.getList()
      },
      handleModifyStatus(row: any, status: string) {
         let jumpData = { type: "队伍点",name:row.title,lng:row.sourceURL,lat:row.imageURL};
        router.push({
					path: '/menu/menu1/menu12/menu127',
					query: jumpData,
				})
      },
      sortChange(data: any) {
        const { prop, order } = data
        if (prop === 'id') {
          dataMap.sortByID(order)
        }
      },
      sortByID(order: string) {
        if (order === 'ascending') {
          dataMap.listQuery.sort = '+id'
        } else {
          dataMap.listQuery.sort = '-id'
        }
        dataMap.handleFilter()
      },
      getSortClass(key: string) {
        const sort = dataMap.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      },
      resetTempArticleModel() {
        dataMap.tempArticleModel = cloneDeep(defaultArticleModel);
         dataMap.rowlist = [
            {
              id:Math.random(),
              rowZero: '',
              rowTwo: '',
              rowOne:''
            }
          ];
      },
      handleCreate() {
        router.push({
					path: '/menu/menu1/menu12/menu127',
					query: { type: "队伍点",name:''},	})
      //  dataMap.dialogStatus = 'create';
      //   dataMap.dialogFormVisible = true;
      //   (dialogPop.value as any).handleCreate();
      },
      async createData(tempArticleModel:any,rowlist:any) {
          await createArticle({...tempArticleModel,fullContent:JSON.stringify(rowlist)},ArticleType.ZYDW).then(async() => {
		        ElMessage.success('添加成功')
		        dataMap.dialogFormVisible = false
		        const data = await getArticles(dataMap.listQuery,ArticleType.ZYDW)
		        //const data=zhihuiJigouJson        
		        dataMap.list = data?.data ?? []
		        dataMap.total = data?.total ?? 0
		      }).catch(err => {
		      ElMessage.warning('添加错误')
		     });
      },
       onAddRow() {
        dataMap.rowlist.push({
          id:Math.random(),
          rowZero: '',
          rowTwo: '',
          rowOne:''
        });
		  },
      // 删除行
      onDelRow(index){
        dataMap.rowlist.splice(index, 1);
      },
      handleUpdate(row: any) {
         dataMap.dialogStatus = 'update';
        dataMap.dialogFormVisible = true;
        (dialogPop.value as any).handleUpdate(row);
      },
      async updateData(tempArticleModel,rowlist) {
           await updateArticle({...tempArticleModel,fullContent:JSON.stringify(rowlist)},ArticleType.ZYDW).then(async()=>{
	        	ElMessage.success('更新成功')
		        dataMap.dialogFormVisible = false
		        const data = await getArticles(dataMap.listQuery,ArticleType.ZYDW)		                
		        dataMap.list = data?.data ?? []
		        dataMap.total = data?.total ?? 0	
            }).catch(err => {
		      ElMessage.warning('更新失败')
		    });
      },
       async handleDelete(row: any, index: number) {
          await deleteArticle(row.id,ArticleType.ZYDW).then(()=>{
          ElMessage.success({
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          dataMap.list.splice(index, 1);
        }).catch(err => {
	      ElMessage.warning('删除失败')
	     });
      },
      async handleGetPageviews(pageviews: string) {
        const data = await getPageviews({ pageviews })
        //const data = zhihuiJigouJson.data;
        dataMap.pageviewsData = data?.data.pageviews
        console.log(dataMap.pageviewsData)
        dataMap.dialogPageviewsVisible = true
      },
      handleDownload() {
        dataMap.downloadLoading = true
        const tHeader = ['编号','电话' ,'名称', '类型',"管理单位","人数","组织建制"]
        const filterVal = [
          'abstractContent',
          'timestamp',
          'title',
          'author',
          'importance',
          'pageviews',
          'status'
        ];
        const filterValtwo = [
          'rowZero',
          'rowOne',
          'rowTwo',
        ];
        let data = formatJson(filterVal, dataMap.list,true);

        let jsonArr:any[] = [];

        for (let index = 0; index < data.length; index++) {
           const element = data[index];
           if(index !=0)
           jsonArr.push(tHeader);
           jsonArr.push(element);
           jsonArr.push(["人员","号码","备注","","",""]);
           try{
              let arr = JSON.parse(dataMap.list[index].fullContent);
              let rowData = formatJson(filterValtwo,arr,true);
              jsonArr.push(...rowData);
            }catch{
            }
        }
        exportJson2Excel(tHeader, jsonArr, "专业队伍", undefined, undefined, true, "xlsx");
        dataMap.downloadLoading = false;
      },
      typeFilter: (type: string) => {
        return calendarTypeKeyValue[type]
      }
    })
    onMounted(() => {
      console.log(typeof ElForm)
      dataMap.getList(null, null, 10)
    })
    return { t,...toRefs(dataMap), dataForm,dialogPop }
  }
})
</script>
